import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter)

//1.导入组件
import login from '../views/user/login.vue'

import layout from '../views/layout.vue'
import home from '../views/home/home.vue'
import movie from '../views/movie/movie.vue'
import qa from '../views/qa/qa.vue'
import user from '../views/user/user.vue'
import notfound from '../views/notfound/notfound.vue'
import { getToken } from '../utils/token'

const routes = [
  {
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'layout',
    path: '/',
    component: layout,
    children: [
      {
        name: 'home',
        path: '/home',
        component: home
      },
      {
        name: 'movie',
        path: '/movie',
        component: movie
      },
      {
        name: 'qa',
        path: '/qa',
        component: qa
      },
      {
        name: 'user',
        path: '/user',
        component: user,
        //添加路由守卫的元信息
        meta:{
          isLogin:true
        }
      },
      {
        path: '/',
        redirect: '/home'
      }
    ]
  },
  {
    //注册无法访问组件
    name: 'notfound',
    path: '/notfound',
    component: notfound
  },
  {
    path: '*',
    redirect: '/notfound'
  }

]

const router = new VueRouter({
  routes
})


//设置路由前置守卫
router.beforeEach((to, from, next) => {
  // 判断用户没有没有登录
  if(to.meta.isLogin && !getToken()){
    //没有登录token值，则跳转到登录页面
    next({path:'/login'})
  }else{
    //有登录token值，则进入用户信息正常跳转页
    next()
  }
})

export default router
